/*
 * @Author: 胡海
 * @Date: 2020-02-10 19:39:49
 * @LastEditors: 胡海
 * @LastEditTime: 2020-03-07 22:41:57
 * @Description: 
 */
const Router = require('koa-router')
const {
    TokenValidator,
    NotEmptyValidator
} = require('../../validators/validator')

const {
    generateToken
} = require('../../../core/util')
const {
    Auth
} = require('../../../middlewares/auth')
const {
    User
} = require('../../models/user')

const router = new Router({
    prefix: '/v1/token'
})

router.post('/', async (ctx) => { // token路由
    const v = await new TokenValidator().validate(ctx, {
        account: 'username',
        secret: 'password'
    })
    let user = {
        username: v.get('body.username'),
        password: v.get('body.password'),
    }
    let token;
    token = await emailLogin(user.username, user.password)
    ctx.body = {
        error_code: 0,
        msg: '登录成功',
        data: {
            token
        }
    }
})

router.post('/verify', async (ctx) => { // token 验证
    // token
    const v = await new NotEmptyValidator().validate(ctx)
    const result = Auth.verifyToken(v.get('body.token'))
    ctx.body = {
        is_valid: result
    }
})

async function emailLogin(username, password) { // token
    const user = await User.verifyUserPassword(username, password)
    return token = generateToken(user.id, 2)
}

module.exports = router